using System;
using System.Collections.Generic;
using Microsoft.Practices.Composite.Events;
using Silverlight.Weblog.Client.DAL.Events;
using Silverlight.Weblog.Client.DAL.ViewModel;
using Silverlight.Weblog.Common.IoC;
using Silverlight.Weblog.Server.DAL;
using System.Linq;

namespace Silverlight.Weblog.Client.Default.Widgets
{
    public class CategoriesSiderbarWidgetViewModel : ViewModelBase, ICategoriesSiderbarWidgetViewModel, IDisposable
    {
        public CategoriesSiderbarWidgetViewModel()
        {
            IoC.Get<IEventAggregator>().GetEvent<InitiaPayloadLoadedEvent>().Subscribe(UpdateViewModel);
        }

        public void UpdateViewModel(User obj)
        {
            this.Model = obj;
        }

        #region Model
        private User _model;
        public User Model
        {
            get { return _model; }
            set
            {
                if (_model != value)
                {
                    _model = value;
                    RaisePropertyChanged("Model");
                    RaisePropertyChanged((CategoriesSiderbarWidgetViewModel vm) => vm.ChildrenCategories);
                }

            }
        }
        #endregion Model

        public IEnumerable<CategorySiderbarWidgetViewModel> ChildrenCategories
        {
            get
            {
                if (Model != null)
                    foreach (Category curParentlessCategory in Model.Categories.Where(c => c.ParentCategory == null))
                        yield return new CategorySiderbarWidgetViewModel(curParentlessCategory);
            }
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            IoC.Get<IEventAggregator>().GetEvent<InitiaPayloadLoadedEvent>().Unsubscribe(UpdateViewModel);
        }

        #endregion
    }
}